$(function () {
    layui.use(['element', 'layer'], function () {
        var element = layui.element;

        //生成左侧菜单
        initMenu(".navBar", element, getMenu());

        sideChange();

        addTag(layui);

        delTab(element)
    });
});

/* 添加菜单点击 */
function addTag(layui) {
// 添加新窗口
    $("body").on("click", ".layui-nav .layui-nav-item a:not('.mobileTopLevelMenus .layui-nav-item a')", function () {
        //如果不存在子级
        if ($(this).siblings().length == 0) {
            addTab($(this), layui);
            $('body').removeClass('site-mobile');  //移动端点击菜单关闭菜单层
        }
        $(this).parent("li").siblings().removeClass("layui-nav-itemed");
    })
}

var tabIdIndex = 0;
var menu = [];
var layId;

/* 删除标签 */
function delTab(element) {
    $("body").on("click", ".top_tab li i.layui-tab-close", function () {
        //删除tab后重置session中的menu和curmenu
        liIndex = $(this).parent("li").index();
        var menu = JSON.parse(window.sessionStorage.getItem("menu"));
        if (menu != null) {
            //获取被删除元素
            delMenu = menu[liIndex - 1];
            var curmenu = window.sessionStorage.getItem("curmenu") == "undefined" ? undefined : window.sessionStorage.getItem("curmenu") == "" ? '' : JSON.parse(window.sessionStorage.getItem("curmenu"));
            if (JSON.stringify(curmenu) != JSON.stringify(menu[liIndex - 1])) {  //如果删除的不是当前选中的tab
                // window.sessionStorage.setItem("curmenu",JSON.stringify(curmenu));
                curNav = JSON.stringify(curmenu);
            } else {
                if ($(this).parent("li").length > liIndex) {
                    window.sessionStorage.setItem("curmenu", curmenu);
                    curNav = curmenu;
                } else {
                    window.sessionStorage.setItem("curmenu", JSON.stringify(menu[liIndex - 1]));
                    curNav = JSON.stringify(menu[liIndex - 1]);
                }
            }
            menu.splice((liIndex - 1), 1);
            window.sessionStorage.setItem("menu", JSON.stringify(menu));
        }
        element.tabDelete("bodyTab", $(this).parent("li").attr("lay-id")).init();
    })
}

/* 添加新标签 */
function addTab(_this, layui) {
    if (window.sessionStorage.getItem("menu")) {
        menu = JSON.parse(window.sessionStorage.getItem("menu"));
    }
    var element = layui.element;
    var layer = layui.layer;
    var that = this;
    var openTabNum = 8;
    var tabFilter = "bodyTab";
    if (_this.attr("target") == "_blank") {
        window.open(_this.attr("data-url"));
    } else if (_this.attr("data-url") != undefined) {
        var title = '';
        if (_this.find("i.seraph,i.layui-icon").attr("data-icon") != undefined) {
            if (_this.find("i.seraph").attr("data-icon") != undefined) {
                title += '<i class="seraph ' + _this.find("i.seraph").attr("data-icon") + '"></i>';
            } else {
                title += '<i class="layui-icon">' + _this.find("i.layui-icon").attr("data-icon") + '</i>';
            }
        }
        //已打开的窗口中不存在
        if (hasTab(_this.find("cite").text()) == -1 && _this.siblings("dl.layui-nav-child").length == 0) {
            if ($(".layui-tab-title.top_tab li").length == openTabNum) {
                layer.msg('只能同时打开' + openTabNum + '个选项卡哦。不然系统会卡的！');
                return;
            }
            tabIdIndex++;
            title += '<cite>' + _this.find("cite").text() + '</cite>';
            title += '<i class="layui-icon layui-unselect layui-tab-close" data-id="' + tabIdIndex + '">&#x1006;</i>';
            element.tabAdd(tabFilter, {
                title: title,
                content: "<iframe src='" + _this.attr("data-url") + "' data-id='" + tabIdIndex + "'></iframe>",
                id: new Date().getTime()
            })
            //当前窗口内容
            var curmenu = {
                "icon": _this.find("i.seraph").attr("data-icon") != undefined ? _this.find("i.seraph").attr("data-icon") : _this.find("i.layui-icon").attr("data-icon"),
                "title": _this.find("cite").text(),
                "href": _this.attr("data-url"),
                "layId": new Date().getTime()
            }
            menu.push(curmenu);
            window.sessionStorage.setItem("menu", JSON.stringify(menu)); //打开的窗口
            window.sessionStorage.setItem("curmenu", JSON.stringify(curmenu));  //当前的窗口
            element.tabChange(tabFilter, getLayUIId(_this.find("cite").text()));
            // that.tabMove(); //顶部窗口是否可滚动
        } else {
            //当前窗口内容
            var curmenu = {
                "icon": _this.find("i.seraph").attr("data-icon") != undefined ? _this.find("i.seraph").attr("data-icon") : _this.find("i.layui-icon").attr("data-icon"),
                "title": _this.find("cite").text(),
                "href": _this.attr("data-url")
            }
            // that.changeRegresh(_this.parent('.layui-nav-item').index());
            window.sessionStorage.setItem("curmenu", JSON.stringify(curmenu));  //当前的窗口
            element.tabChange(tabFilter, getLayUIId(_this.find("cite").text()));
        }
    }
}

/* 通过title获取layuiid */
function getLayUIId(title) {
    $(".layui-tab-title.top_tab li").each(function () {
        if ($(this).find("cite").text() == title) {
            layId = $(this).attr("lay-id");
        }
    })
    return layId;
}

/* 判断右侧是否有标签 */
function hasTab(title) {
    var tabIndex = -1;
    $(".layui-tab-title.top_tab li").each(function () {
        if ($(this).find("cite").text() == title) {
            tabIndex = 1;
        }
    })
    return tabIndex;
}

/* 显示隐藏菜单栏 */
function sideChange() {
    var flag = true;
    $("#sideChange").click(function () {
        flag = !flag;
        if (flag) {
            $(this).removeClass("layui-icon-spread-left");
            $(this).addClass("layui-icon-shrink-right");
            $(".layui-side").css("left", "0");
            $(".layui-body").css("left", "200px");
            $(".footer").css("left", "200px");
        } else {
            $(this).removeClass("layui-icon-shrink-right");
            $(this).addClass("layui-icon-spread-left");
            $(".layui-side").css("left", "-260px");
            $(".layui-body").css("left", "0");
            $(".footer").css("left", "0");
        }
    })
}

/* 获取菜单数据 */
function getMenu() {
    var menu = [{
        "title": "文章列表",
        "icon": "&#xe63c",
        "href": "page/news/newsList.html",
        "spread": true
    }, {
        "title": "友情链接",
        "icon": "&#xe64c;",
        "href": "page/links/linksList.html",
        "spread": true
    }, {
        "title": "系统基本参数",
        "icon": "&#xe631;",
        "href": "page/systemParameter/systemParameter.html",
        "spread": true
    }, {
        "title": "其他页面",
        "icon": "&#xe630;",
        "href": "",
        "spread": false,
        "children": [
            {
                "title": "404页面",
                "icon": "&#xe61c;",
                "href": "page/404.html",
                "spread": false
            },
            {
                "title": "登录",
                "icon": "&#xe609;",
                "href": "page/login/login.html",
                "spread": false,
                "target": "_blank"
            }
        ]
    }];
    return menu;
}

/* 初始化菜单 */
function initMenu(prop, element, strData) {
    var data;
    if (typeof (strData) == "string") {
        var data = JSON.parse(strData); //部分用户解析出来的是字符串，转换一下
    } else {
        data = strData;
    }
    console.log(data)
    var ulHtml = '';
    for (var i = 0; i < data.length; i++) {
        if (data[i].spread || data[i].spread == undefined) {
            ulHtml += '<li class="layui-nav-item layui-nav-itemed">';
        } else {
            ulHtml += '<li class="layui-nav-item">';
        }
        if (data[i].children != undefined && data[i].children.length > 0) {
            ulHtml += '<a>';
            if (data[i].icon != undefined && data[i].icon != '') {
                if (data[i].icon.indexOf("icon-") != -1) {
                    ulHtml += '<i class="seraph ' + data[i].icon + '" data-icon="' + data[i].icon + '"></i>';
                } else {
                    ulHtml += '<i class="layui-icon" data-icon="' + data[i].icon + '">' + data[i].icon + '</i>';
                }
            }
            ulHtml += '<cite>' + data[i].title + '</cite>';
            ulHtml += '<span class="layui-nav-more"></span>';
            ulHtml += '</a>';
            ulHtml += '<dl class="layui-nav-child">';
            for (var j = 0; j < data[i].children.length; j++) {
                if (data[i].children[j].target == "_blank") {
                    ulHtml += '<dd><a data-url="' + data[i].children[j].href + '" target="' + data[i].children[j].target + '">';
                } else {
                    ulHtml += '<dd><a data-url="' + data[i].children[j].href + '">';
                }
                if (data[i].children[j].icon != undefined && data[i].children[j].icon != '') {
                    if (data[i].children[j].icon.indexOf("icon-") != -1) {
                        ulHtml += '<i class="seraph ' + data[i].children[j].icon + '" data-icon="' + data[i].children[j].icon + '"></i>';
                    } else {
                        ulHtml += '<i class="layui-icon" data-icon="' + data[i].children[j].icon + '">' + data[i].children[j].icon + '</i>';
                    }
                }
                ulHtml += '<cite>' + data[i].children[j].title + '</cite></a></dd>';
            }
            ulHtml += "</dl>";
        } else {
            if (data[i].target == "_blank") {
                ulHtml += '<a data-url="' + data[i].href + '" target="' + data[i].target + '">';
            } else {
                ulHtml += '<a data-url="' + data[i].href + '">';
            }
            if (data[i].icon != undefined && data[i].icon != '') {
                if (data[i].icon.indexOf("icon-") != -1) {
                    ulHtml += '<i class="seraph ' + data[i].icon + '" data-icon="' + data[i].icon + '"></i>';
                } else {
                    ulHtml += '<i class="layui-icon" data-icon="' + data[i].icon + '">' + data[i].icon + '</i>';
                }
            }
            ulHtml += '<cite>' + data[i].title + '</cite></a>';
        }
        ulHtml += '</li>';
    }

    $(prop).find('ul').html('<li class="layui-nav-item layui-this"><a data-url="page/main.html"><i class="layui-icon" data-icon=""></i><cite>控制台</cite></a></li>').append(ulHtml);
    element.init();  //初始化页面元素
    $(window).resize(function () {
        $(".navBar").height($(window).height() - 210);
    });
}
